package com.zhny.aiot.led.four.screen.plugin.model;

import com.zhny.aiot.led.four.screen.plugin.config.LedConfig;
import com.zhny.aiot.plugin.core.utils.CRCUtils;
import com.zhny.aiot.plugin.udc.command.IUdcPrivateRequestMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

public class LedCommand implements IUdcPrivateRequestMessage {
    private LedConfig config;
    private final int cmd;
    private final ByteBuf ledData;

    public LedCommand (LedConfig config, int cmd, ByteBuf ledData){
        this.config=config;
        this.cmd=cmd;
        this.ledData=ledData;
    }

//    @Override
//    public int getLength() {
//        return ledData.readableBytes () + 18;
//    }

    @Override
    public ByteBuf encoder() {
        ByteBuf dataBuf =Unpooled.buffer(128);
        dataBuf.writeByte(0x78);
        dataBuf.writeByte(0x34);
        dataBuf.writeShortLE(config.getAddress());
        dataBuf.writeByte(cmd);
        dataBuf.writeShort(0);
        dataBuf.writeShort(0);
        dataBuf.writeShort(0);
        dataBuf.writeShort(0);
        dataBuf.writeShortLE ((ledData != null?ledData.readableBytes():0));
        if(ledData != null)
            dataBuf.writeBytes(ledData);
        int crc =CRCUtils.calculateCRC(dataBuf,0,dataBuf.readableBytes());
        dataBuf.writeShort(crc);
        dataBuf.writeByte(0xa5);
        return dataBuf;
    }

    @Override
    public String getKey() {
        return null;
    }
}
